// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: xguo

#include "appcoin2/support/order/py_trade_client.h"

#include <memory>
#include <string>
#include <utility>

namespace appcoin2::support::order {

namespace {

template <typename T>
bool ConvertProtosToString(
    const std::vector<T>& in, std::vector<pybind11::bytes>& out) {
  bool ret = true;
  out.clear();
  for (const auto& elem : in) {
    std::string dst;
    ret = elem.SerializeToString(&dst);
    if (!ret) {
      out.clear();
      break;
    } else {
      out.push_back(pybind11::bytes(dst));
    }
  }
  return ret;
}

}

PyTradeClient::PyTradeClient(const std::string os_config_str) {
  coin2::exchange::order::OrderSystemConfig osc_config;
  bool ret = osc_config.ParseFromString(os_config_str);
  CHECK_THROW(ret);
  client_.reset(new ::coin2::exchange::base::order::SyncTradeClient(osc_config));
}

std::vector<pybind11::bytes> PyTradeClient::QueryTransferHistories(
    int64_t start_timestamp, int64_t end_timestamp) {
  std::vector<coin::proto::CurrencyTransferElement> transfer_out;
  client_->QueryTransferHistories(start_timestamp, end_timestamp, &transfer_out);
  std::vector<pybind11::bytes> rsp;
  CHECK_THROW(ConvertProtosToString(transfer_out, rsp));
  return rsp;
}

PYBIND11_MODULE(py_trade_client, m) {
  using appcoin2::support::order::PyTradeClient;

  // private client
  pybind11::class_<PyTradeClient>(m, "PyTradeClient")
      .def(pybind11::init<const std::string>())
      .def("query_transfer_histories", &PyTradeClient::QueryTransferHistories);
};

}  // namespace appcoin2::support::order
